package com.pickgliss.loader
{
	import com.pickgliss.ui.ComponentSetting;
	import com.pickgliss.ui.core.Component;
	import com.pickgliss.utils.StringUtils;
	
	import flash.events.Event;
	import flash.external.ExternalInterface;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	
	public class ModuleLoader extends DisplayLoader
	{
		public function ModuleLoader(id:int, url:String)
		{
			super(id, url);
		}
		
		public static function decry(src:ByteArray):ByteArray
		{
			var bytes:ByteArray = new ByteArray();
			bytes.writeByte(67);
			bytes.writeByte(87);
			bytes.writeByte(83);
			src.position = 21;
			src.readBytes(bytes,124,src.bytesAvailable -121);
			src.readBytes(bytes,3);
			return bytes;
		}
		
		public static function getDefinition(classname:String):*
		{
			return DisplayLoader.Context.applicationDomain.getDefinition(classname);
		}
		
		public static function hasDefinition(classname:String):Boolean
		{
			return DisplayLoader.Context.applicationDomain.hasDefinition(classname);
		}
		
		override public function loadFromBytes(data:ByteArray):void
		{
			_starTime = getTimer();
			_displayLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,__onContentLoadComplete);
			dispatchEvent(new LoaderEvent(LoaderEvent.PROGRESS,this));
			analyMd5(data);
		}
		
		override protected function __onDataLoadComplete(event:Event):void
		{
			trace("文件加载完成： ： ：" + _url);
			removeEvent();
			try
			{
				_loader.close();
			}
			catch(err :Error){}
			if(_loader.data.length == 0)
				return;
			_displayLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,__onContentLoadComplete);
			analyMd5(_loader.data);
		}
		
		private var _isSecondLoad:Boolean;
		public function analyMd5(content:ByteArray):void
		{
			var md5:String = ComponentSetting.getUrlMd5(_url);
			if(ComponentSetting.checkNeedAnalyzeMd5(md5))
			{
				var isRight:Boolean = true;
				if(UiConfigAnalyzer.data)
				{
					var fileName:String = ComponentSetting.getMD5FileNameByFilePath(_url);
					var size:int = int(UiConfigAnalyzer.data[fileName]);
					if(size != 0)
						isRight = (Math.abs(size - content.bytesAvailable) < 3000);
				}
				trace("文件需要解码md5： ： ：" + _url);
				if(ComponentSetting.compareMD5(content,md5) && isRight)
				{
					trace("文件解码md5成功5： ： ：" + _url);
					//比对成功
					var temp:ByteArray = new ByteArray();
					content.position = 37;
					content.readBytes(temp);
					handleModule(temp,md5);
				}
				else
				{
					//重新加载
					if(_isSecondLoad)
					{
						fireCompleteEvent();
					}
					else
					{//如果使用cdn则要回源去加载
//						_url = _url.replace(ComponentSetting.RESOURCE_PATH, ComponentSetting.BACKUP_RESOURCE_PATH);
						_isLoading = false;
						addEvent();
						if(_url.indexOf("?") >= 0)
							_url += ('rnd=' + Math.random());
						else
							_url += ('?rnd=' + Math.random());
						startLoad(_url);
					}
					_isSecondLoad = true;
				}
			}
			else
			{
				trace("文件不需要解码md5： ： ：" + _url);
				handleModule(content,md5);
			}
		}
		
		private function handleModule(temp:ByteArray,md5:String = ""):void
		{
			temp.position = 0;
			if((temp[0] != 67) || (temp[1] != 87) || (temp[2] != 83))
			{
				temp = decry(temp);
			}
			if(temp)temp.position = 0;
			_displayLoader.loadBytes(temp,Context);
			LoaderSavingManager.cacheFile(_url,_loader.data,false,md5);
		}
		
		override public function get type():int
		{
			return BaseLoader.MODULE_LOADER;
		}
		override protected function __onContentLoadComplete(event:Event):void
		{
			trace("文件可正确使用： ： ：" + url);
			super.__onContentLoadComplete(event);
			var key:String = StringUtils.substrSwfName(url);
			LoaderManager.Instance.loadedResource[key] = true;
			dispose();
		}
	}
}